<?php
/**
 * sfActionsFnde extends sfActions and implements methods to filter
 * and pagination.
 *
 */
class sfActionsFoxsis extends sfActions
{

    const MSG_FILTRAGEM_EFETUADA  = 'Filtragem Efetuada.';
    const FILTER_INSTANCE_NAME = 'filter';
    const FILTER_HTML_KEY = 'filter';
    const FILTER_SESSION_USER_ATTRIBUTE = 'filter';

    const FILTER_SUCCESS = 1;
    const FILTER_ERROR =   2;
    const LIMIT_PAGE_DATA_TABLE = 10;

    ### UTIL

    public function getRequestParameter($name, $default = null)
    {
        if(is_array($name)) {
            $valor = $this->requestParameterHolder->get($name[0]);
            if(isset($valor[$name[1]])) {
                return $valor[$name[1]];
            }
            else {
                return $default;
            }
        }
        else {
            return $this->requestParameterHolder->get($name, $default);
        }
    }

	public function setJSONJqGrid($data, $id)
    {
    	$output	= array('total' 	=> ceil(count($data)/NUM_LIST_ITENS),
    					'page'		=> $this->getRequestParameter('page'),
    					'records'	=> count($data),
    					'rows'		=> array()
    					);

    	foreach($data as $chave => $dados)
    	{
    		$output['rows'][$chave]['id']	= $dados[$id];

    		foreach($dados as $coluna => $valor)
    			$output['rows'][$chave]['cell'][] = $valor;
    	}

    	$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
      	return $this->renderText(json_encode($output));
    }

	public function getRequestDataTable()
    {
    	$return	= array();

    	//Colunas
    	$this->colunas		= $this->getRequestParameter('columns');

    	//Ordenação
    	$array_colunas		= explode(",", $this->colunas);
		$this->order		= array('coluna' => $array_colunas[$this->getRequestParameter('iSortCol_0')],
									'direcao' => $this->getRequestParameter('sSortDir_0'));

		$this->search		= $this->getRequestParameter('sSearch');

		$this->filter      			= $this->_getFilter();
		$this->filter['search']		= $this->search;

		$this->page_num				= $this->getRequestParameter('iDisplayStart')+1;

		return $return;

    }


  public function paginadorDataTable($list, $paginaAtual = null, $limit = LIMIT_PAGE_DATA_TABLE)
  {
       ## cria o paginador

        $this->getContext()->getConfiguration()->loadHelpers('Url');

		$this->pager_layout = new Foxsis_Pager_Layout(
			$pager = new Doctrine_Pager(
				$list,
				($paginaAtual != null) ? $paginaAtual : $this->_setActualPage(),
				$limit
			),
			new Doctrine_Pager_Range_Sliding(array('chunk' => MAX_PAGER_LINKS)),
			url_for('produto/tortas')
		);

        ## executa a consulta
        $this->content = $this->pager_layout->execute(array(), Doctrine::HYDRATE_ARRAY);

        return  $this->content;
  }

	public function setJSONDataTable($data, $colunas, $total_linhas)
    {
    	$output = array(
						"sEcho" 				=> intval($this->getRequestParameter('sEcho')),
						"iTotalRecords" 		=> $total_linhas,
    					"sColumns"				=> $colunas,
						"iTotalDisplayRecords" 	=> ceil($total_linhas/self::LIMIT_PAGE_DATA_TABLE),
						"aaData" 				=> array()
					);


	   	foreach($data as $chave => $dados)
	 		$output['aaData'][] = $dados;

    	$this->getResponse()->setHttpHeader('Content-type','application/json; charset=utf-8');
      	return $this->renderText(json_encode($output));
    }

      protected function enviarEmail($subject, $content, $to = array())
    {
         try
        {
            $mail = new sfMail();
            $mail->setCharset('iso-8859-1');

            $mail->setSender(sfConfig::get('app_email_sistema'));
            $mail->setFrom(sfConfig::get('app_email_sistema'));
            $mail->addReplyTo(sfConfig::get('app_email_sistema'));

            foreach($to as $t)
                $mail->addAddress($t);

            $mail->setSubject(utf8_decode("[Doce Chalé] ".$subject));
            $mail->setContentType('text/html');
            $mail->setBody($content);
            $mail->send();

        }
        catch(Exception $e)
        {
            mail('andreymor@gmail.com', 'Erro na compra', $e->getMessage());
        }

    }



  public function carregarPaginador($list, $paginaAtual = null, $limit = 6)
  {
       ## cria o paginador

        $this->getContext()->getConfiguration()->loadHelpers('Url');
		$this->pager_layout = new Foxsis_Pager_Layout(
			$pager = new Doctrine_Pager(
				$list,
				($paginaAtual != null) ? $paginaAtual : $this->_setActualPage(),
				$limit
			),
			new Doctrine_Pager_Range_Sliding(array('chunk' => MAX_PAGER_LINKS)),
			url_for('produto/tortas')
		);

        ## executa a consulta
        $this->content = $this->pager_layout->execute(array(), Doctrine::HYDRATE_ARRAY);

        return  $this->content;
  }

    public function erroGenerico() {
        print_r($this->getRequest()->getErrors());
        die();
    }
    ### FILTROS E PAGINA��O

    /**
     * Set the actual page in the session if this is not setted
     *
     * @return actual page
     */
    protected function _setActualPage() {
        $ns = $this->getModuleName();
        if($this->hasRequestParameter('pg_num')) {
            $paginaAtual = $this->getRequestParameter('pg_num');
        }
        else {
            $paginaAtual =
            $this->getUser()->getAttribute('pg_num',1,$ns);
        }
        $this->getUser()->setAttribute('pg_num',$paginaAtual,$ns);
        return $paginaAtual;
    }

    /**
     * Get the filter from or create a new in the session
     *
     * @param array $defaultValues
     * @return filter
     */

    protected function _getFilter($defaultValues = array()) {
        $ns = $this->getModuleName();
        if($this->getUser()->hasAttribute(self::FILTER_SESSION_USER_ATTRIBUTE,$ns)) {
            $filter = unserialize(
            $this->getUser()->getAttribute(self::FILTER_SESSION_USER_ATTRIBUTE,null,$ns)
            );
        }
        else {
            $filter = new Filtro(
            array(),
            $defaultValues
            );
            $filter->setCulture($this->getUser()->getCulture());
        }
        return $filter;
    }

    public function executeFilter() {
        $ns = $this->getModuleName();
        $filter = new Filtro(
        $this->getRequestParameter(self::FILTER_SESSION_USER_ATTRIBUTE)
        );
        $filter->setCulture($this->getUser()->getCulture());
        $this->getUser()->setAttribute('pg_num',1,$ns);
        $this->setFlash('mensagem',self::MSG_FILTRAGEM_EFETUADA,false);
        $this->getUser()->setAttribute(
        self::FILTER_SESSION_USER_ATTRIBUTE,
        serialize($filter),
        $ns
        );
        return $this->route(self::FILTER_SUCCESS);
    }

    public function handleErrorFilter()
    {
        return $this->route(self::FILTER_ERROR);
    }


    /**
     * Sets a flash variable that will be passed to the very next action.
     *
     * @param  string  The name of the flash variable
     * @param  string  The value of the flash variable
     * @param  boolean true if the flash have to persist for the following request (true by default)
     */
    public function setFlash($name, $value, $persist = true)
    {
        $this->getUser()->setFlash($name, $value, $persist);
    }

    /**
     * Gets a flash variable.
     *
     * @param  string The name of the flash variable
     *
     * @return mixed The value of the flash variable
     */
    public function getFlash($name)
    {
        return $this->getUser()->getFlash($name);
    }

    /**
     * Returns true if a flash variable of the specified name exists.
     *
     * @param  string The name of the flash variable
     *
     * @return boolean   true if the variable exists, false otherwise
     */
    public function hasFlash($name)
    {
        return $this->getUser()->hasFlash($name);
    }
}
?>